package com.common.library.util;

import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Locale;
import java.util.Properties;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.util.Log;

import com.zs4sdk.Zs4GameBase;
import com.zs4sdk.common.Extra;
import com.common.library.data.CommonEventHandler.ResultHandlerInEvent;
import com.common.library.data.EventHandler2Get;
import com.common.library.data.EventHandler2Post;
import com.zs4sdk.entity.Zs4GameData;
//import com.tencent.mm.sdk.openapi.IWXAPI;
//import com.tencent.mm.sdk.openapi.SendMessageToWX;
//import com.tencent.mm.sdk.openapi.WXAPIFactory;
//import com.tencent.mm.sdk.openapi.WXMediaMessage;
//import com.tencent.mm.sdk.openapi.WXWebpageObject;

/**
 * 
 * function: 项目帮助类
 * 
 * @ author: aXiBa
 */
public class ProjectHelper {
	
	private static final String TAG = ProjectHelper.class.getSimpleName();

    /**微信朋友圈支持的版本*/
    private static final int TIMELINE_SUPPORTED_VERSION = 0x21020001;
	
	private static HashMap<String, HashMap<String, String>> langMapping = null;   // 语言配置

    /**
     * 获取网络图片
     * @param path
     * @return
     */
    public static Bitmap getNetworkImage(String path) {

        try {
            URL url = new URL(path);
            String responseCode = url.openConnection().getHeaderField(0);

            if (responseCode.indexOf("200") < 0) {
                Log.i("获取网络图片异常","图片文件不存在或路径错误，错误代码：" + responseCode);
                return null;
            }

            return BitmapFactory.decodeStream(url.openStream());

        } catch (IOException e) {
            e.printStackTrace();
        }

        return null;

    }

    /**
     * 微信网页分享
     * @param context
     * @param webpageUrl 网页地址
     * @param title 标题
     * @param desc 描述
     * @param bitmap 小图标 缩略图大小是否超过32k
     * @param isTimeline 是否分享到朋友
     */
    public static void shareWechatWebpage(Context context, String webpageUrl, String title, String desc, Bitmap bitmap, Boolean isTimeline) {

//        if(Helper.isEmpty(Zs4GameData.getInstance().getWechatAppId())) {
//            ActivityHelper.showToast(ActivityHelper.getStringResId("zs4gamestring_hint_wechat_appid_empty"));
//            return;
//        }
//
//        IWXAPI api = WXAPIFactory.createWXAPI(context, Zs4GameData.getInstance().getWechatAppId());
//
//        //没有安装微信
//        if(!api.isWXAppInstalled()) {
//            ActivityHelper.showToast(ActivityHelper.getStringResId("zs4gamestring_hint_wechat_uninstall"));
//            return;
//        }
//
//         //api.registerApp(Zs4GameData.getInstance().getWechatAppId());
//
//        //判断是否支持朋友圈分享
//        if(isTimeline) {
//            int wxSdkVersion = api.getWXAppSupportAPI();
//            if(wxSdkVersion < TIMELINE_SUPPORTED_VERSION) {
//                ActivityHelper.showToast(ActivityHelper.getStringResId("zs4gamestring_hint_wechat_unsupport_timeline"));
//                return;
//            }
//        }
//
//        WXWebpageObject webpage = new WXWebpageObject();
//        webpage.webpageUrl = webpageUrl;
//        WXMediaMessage msg = new WXMediaMessage(webpage);
//        msg.title = title;
//        msg.description = desc;
//        if(bitmap != null) {
//            msg.thumbData = getBitmapBytes(bitmap, false);
//        }
//
//        SendMessageToWX.Req req = new SendMessageToWX.Req();
//        req.transaction = "webpage" + System.currentTimeMillis();
//        req.message = msg;
//        //分享到微信朋友圈
//        if(isTimeline) {
//            req.scene = SendMessageToWX.Req.WXSceneTimeline;
//        }else {
//            req.scene = SendMessageToWX.Req.WXSceneSession;
//        }
//
//         api.sendReq(req);
//    }
//
//    /***
//     * bitmap转byte[]
//     * @param bitmap
//     * @param paramBoolean
//     * @return
//     */
//    public static byte[] getBitmapBytes(Bitmap bitmap, boolean paramBoolean) {
//        Bitmap localBitmap = Bitmap.createBitmap(120, 120, Bitmap.Config.RGB_565);
//        Canvas localCanvas = new Canvas(localBitmap);
//        int i;
//        int j;
//        if (bitmap.getHeight() > bitmap.getWidth()) {
//            i = bitmap.getWidth();
//            j = bitmap.getWidth();
//        } else {
//            i = bitmap.getHeight();
//            j = bitmap.getHeight();
//        }
//        while (true) {
//            localCanvas.drawBitmap(bitmap, new Rect(0, 0, i, j), new Rect(0, 0, 120, 120), null);
//            if (paramBoolean)
//                bitmap.recycle();
//            ByteArrayOutputStream localByteArrayOutputStream = new ByteArrayOutputStream();
//            localBitmap.compress(Bitmap.CompressFormat.JPEG, 100,
//                    localByteArrayOutputStream);
//            localBitmap.recycle();
//            byte[] arrayOfByte = localByteArrayOutputStream.toByteArray();
//            try {
//                localByteArrayOutputStream.close();
//                return arrayOfByte;
//            } catch (Exception e) {
//                e.printStackTrace();
//            }
//            i = bitmap.getHeight();
//            j = bitmap.getHeight();
//        }
    }

	/**
	 * 
	 * function: 发送广告点击信息
	 *
	 * @param adsId
	 * 
	 * @ author: aXiBa 2013-3-26 下午4:34:43
	 */
	public static void sendAdsClickInfo(String adsId) {
		
		ArrayList<NameValuePair> paramsList = new ArrayList<NameValuePair>();
		paramsList.add(new BasicNameValuePair("ver", Extra.VERSION_API));
		paramsList.add(new BasicNameValuePair("adcode", adsId));
		paramsList.add(new BasicNameValuePair("data", ParamsHelper.getAdsData()));
		new EventHandler2Post(
				Extra.URL.AD_CLICK_API, 
				paramsList, 
				ParamsHelper.getUserAgent1(), 
				new ResultHandlerInEvent() {
					
					@Override
					public void doResultHanler(JSONObject result) throws JSONException {
						
					}
					
					@Override
					public void doExceptionHandler() {
						
					}
				});
		
	}
	
	
	/**
	 * 
	 * function: 启动报道 
	 *
	 * 
	 * @ author: aXiBa 2013-3-26 下午4:57:19
	 */
	public static void sendAppStartInfo(String offlineInfo) {
		
		ArrayList<NameValuePair> paramsList = new ArrayList<NameValuePair>();
		paramsList.add(new BasicNameValuePair("v", Extra.VERSION_API));
//		paramsList.add(new BasicNameValuePair("data", ParamsHelper.getUserAgent1()));
		if(Helper.isNotEmpty(offlineInfo)) {
			paramsList.add(new BasicNameValuePair("ollog", offlineInfo));
		}
		else {
			paramsList.add(new BasicNameValuePair("ollog", ""));
		}
		
		String old_version = FileUtils.readContent(FileUtils.getInternalFileDir().concat(Extra.FILE_VERION));
		String current_version = ActivityHelper.getCurrentVersionName();
		// 如果是版本更新传2，其它传1
		if(Helper.isNotEmpty(old_version) && !old_version.equals(current_version)) {
			paramsList.add(new BasicNameValuePair("is_device_update", "2"));
		}
		else {
			paramsList.add(new BasicNameValuePair("is_device_update", "1"));
		}
		
		// 保存版本信息
		try {
			FileUtils.writeContent2File(current_version, FileUtils.getInternalFileDir(), Extra.FILE_VERION);
		} catch (IOException e) {
			e.printStackTrace();
			LogUtil.e(TAG, "保存版本信息出错..");
		}
		
		new EventHandler2Get(
				Extra.URL.DEVICE_START_INFO, 
				paramsList, 
				ParamsHelper.getUserAgent1(), 
				new ResultHandlerInEvent() {
					
					@Override
					public void doResultHanler(JSONObject result) throws JSONException {
						LogUtil.i(TAG, "发送报道信息结果：" + result);
						
					}
					
					@Override
					public void doExceptionHandler() {
						
					}
				},
				false);
	}	
	
	
	
	/**
	 * 
	 * function: 安装apk
	 *
	 * @param path
	 * @param ctx
	 * 
	 * @ author: aXiBa 2011-12-26 下午03:24:24
	 */
	public static void installApk(String path, Context ctx) {
		
		Intent intent = new Intent();
		intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		intent.setAction(Intent.ACTION_VIEW);
		
		intent.setDataAndType(Uri.parse("file://" + path), "application/vnd.android.package-archive");
		ctx.startActivity(intent);
		
	}
	
	/**
	 * 
	 * function: 用浏览器下载apk, 或者打开html页面
	 *
	 * @param url
	 * @param context
	 * 
	 * @ author: aXiBa 2012-2-9 上午11:15:29
	 */
	public static void downApkWithBrowse(String url, Context context) {
		
		try {
			Intent intent = new Intent(Intent.ACTION_VIEW); 
			intent.setData(Uri.parse(url));
            context.startActivity(intent);
		} catch (ActivityNotFoundException e) {
			ActivityHelper.showToast(context.getString(Helper.getStringResId(context, Zs4GameBase.getPackageName(), "zs4gamestring_hint_intentview_error")));
		}
	}
	/**
	 * function: 检查apk是否存在
	 * @param context
	 * @param packageName
	 * @return
	 */
	public static boolean checkApkExist(Context context, String packageName)
    {
            if (packageName == null || "".equals(packageName))
            {
                    return false;
            }
            try
            {
                    context.getPackageManager().getApplicationInfo(packageName,PackageManager.GET_UNINSTALLED_PACKAGES);
                    return true;
            }
            catch (NameNotFoundException e)
            {
                    return false;
            }
    }

	/**
	 * 
	 * function: 得到友盟Key
	 *
	 * @param context
	 * @param packageName
	 * @return
	 * 
	 * @ author: aXiBa 2013-4-17 上午11:18:58
	 */
//	public static String getUmengKey(Context context, String packageName) {
//		
//		String umengKey = "";
//		
//		try {
//			ApplicationInfo packageInfo = context.getPackageManager().getApplicationInfo(packageName, PackageManager.GET_META_DATA);
//			
//			if(null != packageInfo) {
//				Bundle metaData = packageInfo.metaData;
//				if(Helper.isNotNull(metaData) && metaData.containsKey("UMENG_APPKEY")) {
//					umengKey = packageInfo.metaData.getString("UMENG_APPKEY");
//					LogUtil.i(TAG, "得到友盟key: " + umengKey);
//				}
//			}
//		} catch (NameNotFoundException e) {
//			// TODO Auto-generated catch block
//			e.printStackTrace();
//		}
//		
//		return umengKey;
//	}
	
	
	/**
	 * 
	 * function: 得到渠道id
	 *
	 * @param context
	 * @return
	 * 
	 * @ author: aXiBa 2013-4-27 下午2:27:04
	 */
	public static String getChannelID(Context context) {
		
		if(!Zs4GameData.getInstance().isReadChannel()) {
			Zs4GameData.getInstance().setChannelID(readChannelID(context));
			Zs4GameData.getInstance().setReadChannel(true);
		}
		
//		LogUtil.i(TAG, "得到渠道id: " + Zs4GameData.getInstance().getChannelID());
		return Zs4GameData.getInstance().getChannelID();
	}
	
	
	/**
	 * 
	 * function: 读取渠道ID
	 *
	 * @param context
	 * @return
	 * 
	 * @ author: aXiBa 2013-5-14 下午2:58:00
	 */
	private static String readChannelID(Context context) {
		
		String channel_id = "";
		
		try {
			InputStream in = context.getAssets().open(Extra.CHANNELINFO.FILENAME);
			
			Properties pro = new Properties();
			
			pro.load(in);
			
			channel_id = pro.getProperty(Extra.CHANNELINFO.PROPERTIEST_KEY);
//			LogUtil.i(TAG, "读取渠道id: " + Zs4GameData.getInstance().getChannelID());
			
		} catch (IOException e) {
//			e.printStackTrace();
		}
		Log.e("chan"," channel_id is "+channel_id);
		return channel_id;
	}
	
	/**
	 * 
	 * 
	 * function: 读取指易付渠道ID
	 *
	 * 
	 * @ author:liPeng 2014-1-8 下午5:17:16
	 */
	public static String readSkyChannelInfo(Context context) {
		
		String channel = Extra.CHANNELINFO.DEFAULT_CHANNEL;
		
		try {
			
			BufferedInputStream bis = new BufferedInputStream(context.getAssets().open(Extra.CHANNELINFO.FILENAME_SKY));
			
			byte[] buffer = new byte[bis.available()];
			bis.read(buffer);
			channel = new String(buffer);

		} catch (IOException e) {
//			e.printStackTrace();
		}
		LogUtil.i("chan", "读取sky渠道id: " + channel);
		return channel;
	}
	
	
	/**
	 * 
	 * function: 设置友盟事件
	 *
	 * @param ctx
	 * @param key
	 * @param name
	 * 
	 * @ author: aXiBa 2013-4-16 下午7:10:04
	 */
//	public static void setUmengEvent(Context ctx, String key, String name) {
//		
//		if(Helper.isNotEmpty(Zs4GameData.getInstance().getUmengKey())) {
//			MobclickAgent.onEvent(ctx, key, name);
//		}
//	}
//	
	
	/**
	 * 
	 * function: 得到语言字符串: "language_country"
	 * 			  匹配到对应的country,使用对应的country String; 否则使用default的country String; 如果default也没有country的就为空。
	 *
	 * @return
	 * 
	 * @ author: aXiBa 2013-5-14 下午1:49:23
	 */
	public static String getLangString() {
		
		String lang = "";
		
		if(Helper.isEmpty(langMapping)) {
			initLangMapping();
		}
		
		String language = Locale.getDefault().getLanguage();
		String country = Locale.getDefault().getCountry();

		lang = language;
		HashMap<String,String> countryMap = langMapping.get(language);
		if(Helper.isNotEmpty(countryMap)) {
			if(countryMap.containsKey(country)) {
				lang += "-" + countryMap.get(country);
			}
			else if(countryMap.containsKey(Extra.KEY_DEFAULT)) {
				lang += "-" + countryMap.get(Extra.KEY_DEFAULT);
			}
		}
		
//		LogUtil.i(TAG, "lang: " + lang);
		return lang;
	}
	
	
	/**
	 * 
	 * function: 初始化有处理的语言列表
	 *
	 * 
	 * @ author: aXiBa 2013-5-14 下午2:21:20
	 */
	public static void initLangMapping() {
		
		langMapping = new HashMap<String, HashMap<String,String>>();
		
		// 中文: 简体，繁体(默认zh_ch)
		HashMap<String,String> map_zh = new HashMap<String, String>();
		map_zh.put(Extra.KEY_DEFAULT, "cn");
		map_zh.put("HANS", "cn");
		map_zh.put("HANT", "tw");
		map_zh.put("TW", "tw");
		langMapping.put("zh", map_zh);
		
	}
}
